<template>
  <div class="product-image-upload">
    <h3>商品图片</h3>
    
    <!-- 图片上传区域 -->
    <div class="upload-section">
      <div class="upload-area" @click="$refs.fileInput.click()" @dragover.prevent @drop.prevent="handleDrop">
        <input 
          type="file" 
          ref="fileInput" 
          multiple 
          accept="image/*" 
          @change="handleFileSelect"
          style="display: none"
        >
        <div class="upload-content">
          <i class="upload-icon">📷</i>
          <p class="upload-text">点击或拖拽上传图片</p>
          <p class="upload-hint">支持 JPG、PNG、GIF 格式，单个文件不超过 5MB</p>
        </div>
      </div>
      
      <!-- 选中文件预览 -->
      <div v-if="selectedFiles.length > 0" class="selected-files">
        <h4>待上传图片 ({{ selectedFiles.length }})</h4>
        <div class="file-list">
          <div v-for="(file, index) in selectedFiles" :key="index" class="file-item">
            <img :src="getFilePreview(file)" alt="预览" class="file-preview">
            <div class="file-info">
              <span class="file-name">{{ file.name }}</span>
              <span class="file-size">{{ formatFileSize(file.size) }}</span>
            </div>
            <button @click="removeSelectedFile(index)" class="btn-remove">×</button>
          </div>
        </div>
        <div class="upload-actions">
          <button 
            @click="uploadSelectedFiles" 
            :disabled="uploading || !shoeId"
            class="btn btn-primary"
          >
            {{ uploading ? '上传中...' : '上传图片' }}
          </button>
          <button @click="clearSelectedFiles" class="btn btn-secondary">清空</button>
        </div>
      </div>
    </div>

    <!-- 已上传图片列表 -->
    <div v-if="images.length > 0" class="uploaded-images">
      <h4>已上传图片 ({{ images.length }})</h4>
      <div class="images-grid">
        <div v-for="image in images" :key="image.imageId" class="image-item">
          <div class="image-wrapper">
            <img :src="getImageUrl(image.imageUrl)" :alt="image.imageName" class="product-image">
            <div class="image-overlay">
              <button 
                @click="setMainImage(image.imageId)" 
                :class="['btn-main', { active: image.isMain }]"
                :disabled="image.isMain"
              >
                {{ image.isMain ? '主图' : '设为主图' }}
              </button>
              <button @click="deleteImage(image.imageId)" class="btn-delete">删除</button>
            </div>
          </div>
          <div class="image-info">
            <p class="image-name">{{ image.imageName }}</p>
            <p class="image-type">{{ image.imageType }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else-if="shoeId && !loading" class="empty-state">
      <i class="empty-icon">🖼️</i>
      <p>暂无图片，请上传商品图片</p>
    </div>

    <!-- 提示信息 -->
    <div v-if="!shoeId" class="info-message">
      <i class="info-icon">ℹ️</i>
      <p>请先保存商品信息后再上传图片</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ProductImageUpload',
  props: {
    shoeId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      images: [],
      selectedFiles: [],
      loading: false,
      uploading: false
    }
  },
  watch: {
    shoeId: {
      handler(newVal) {
        if (newVal) {
          this.loadImages()
        } else {
          this.images = []
        }
      },
      immediate: true
    }
  },
  methods: {
    async loadImages() {
      if (!this.shoeId) return

      this.loading = true
      try {
        const response = await axios.get(`http://localhost:8080/api/v1/shoes/${this.shoeId}/images`)
        if (response.data.code === 200) {
          this.images = response.data.data || []
        }
      } catch (error) {
        console.error('加载图片列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    handleFileSelect(event) {
      const files = Array.from(event.target.files)
      this.addFiles(files)
    },

    handleDrop(event) {
      const files = Array.from(event.dataTransfer.files)
      this.addFiles(files)
    },

    addFiles(files) {
      const imageFiles = files.filter(file => file.type.startsWith('image/'))
      const validFiles = imageFiles.filter(file => {
        if (file.size > 5 * 1024 * 1024) {
          this.$emit('show-message', `文件 ${file.name} 超过 5MB 限制`, 'warning')
          return false
        }
        return true
      })
      
      this.selectedFiles.push(...validFiles)
    },

    removeSelectedFile(index) {
      this.selectedFiles.splice(index, 1)
    },

    clearSelectedFiles() {
      this.selectedFiles = []
      this.$refs.fileInput.value = ''
    },

    getFilePreview(file) {
      return URL.createObjectURL(file)
    },

    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    getImageUrl(url) {
      if (url.startsWith('http')) {
        return url
      }
      return `http://localhost:8080${url}`
    },

    async uploadSelectedFiles() {
      if (this.selectedFiles.length === 0 || !this.shoeId) return

      this.uploading = true
      try {
        const formData = new FormData()
        this.selectedFiles.forEach(file => {
          formData.append('files', file)
        })

        const response = await axios.post(
          `http://localhost:8080/api/v1/shoes/upload-images/${this.shoeId}`,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        )

        if (response.data.code === 200) {
          this.$emit('show-message', '图片上传成功', 'success')
          this.clearSelectedFiles()
          this.loadImages()
        } else {
          this.$emit('show-message', '图片上传失败: ' + response.data.msg, 'error')
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        this.$emit('show-message', '图片上传失败', 'error')
      } finally {
        this.uploading = false
      }
    },

    async setMainImage(imageId) {
      try {
        const response = await axios.post(`http://localhost:8080/api/v1/shoes/set-main-image/${imageId}`)
        if (response.data.code === 200) {
          this.$emit('show-message', '设置主图成功', 'success')
          this.loadImages()
        } else {
          this.$emit('show-message', '设置主图失败: ' + response.data.msg, 'error')
        }
      } catch (error) {
        console.error('设置主图失败:', error)
        this.$emit('show-message', '设置主图失败', 'error')
      }
    },

    async deleteImage(imageId) {
      if (!confirm('确定要删除这张图片吗？')) return

      try {
        const response = await axios.post(`http://localhost:8080/api/v1/shoes/delete-image/${imageId}`)
        if (response.data.code === 200) {
          this.$emit('show-message', '删除图片成功', 'success')
          this.loadImages()
        } else {
          this.$emit('show-message', '删除图片失败: ' + response.data.msg, 'error')
        }
      } catch (error) {
        console.error('删除图片失败:', error)
        this.$emit('show-message', '删除图片失败', 'error')
      }
    }
  }
}
</script>

<style scoped>
.product-image-upload {
  margin-top: 20px;
}

.product-image-upload h3 {
  margin-bottom: 15px;
  color: #333;
  font-size: 18px;
}

.upload-section {
  margin-bottom: 30px;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.upload-area:hover {
  border-color: #3498db;
  background: #f0f8ff;
}

.upload-content {
  pointer-events: none;
}

.upload-icon {
  font-size: 48px;
  display: block;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 16px;
  color: #333;
  margin: 10px 0 5px 0;
}

.upload-hint {
  font-size: 12px;
  color: #666;
  margin: 0;
}

.selected-files {
  margin-top: 20px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.selected-files h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 15px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.file-preview {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.file-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.file-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.file-size {
  font-size: 12px;
  color: #666;
}

.btn-remove {
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-actions {
  display: flex;
  gap: 10px;
}

.uploaded-images h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.image-item {
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  
  transition: transform 0.2s;
}

.image-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.image-wrapper {
  position: relative;
  height: 150px;
  
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.image-wrapper:hover .image-overlay {
  opacity: 1;
}

.btn-main {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  background: #2ecc71;
  color: white;
}

.btn-main.active {
  background: #f39c12;
}

.btn-main:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.btn-delete {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  background: #e74c3c;
  color: white;
}

.image-info {
  padding: 10px;
}

.image-info p {
  margin: 2px 0;
  font-size: 11px;
  color: #666;
}

.image-name {
  font-weight: bold;
  color: #333 !important;
}

.empty-state, .info-message {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.empty-icon, .info-icon {
  font-size: 48px;
  display: block;
  margin-bottom: 10px;
}

.info-message {
  background: #e3f2fd;
  border: 1px solid #bbdefb;
  border-radius: 8px;
  color: #1976d2;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.btn-primary {
  background: #3498db;
  color: white;
}

.btn-primary:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.btn-secondary {
  background: #95a5a6;
  color: white;
}
</style>